import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Input,
  Row,
  Select,
  Modal,
  message,
  Divider,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const FormItem = Form.Item;
const { Option } = Select;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterProblemTypeList: any;
  INITINFO: any;
  checkPerm: any;
  loading: boolean;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  formValues: any;
  orderInfo: any;
  problemDialog: boolean;
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  logisCenterProblemTypeList,
  common: { INITINFO, checkPerm },
  loading,
}: any) => ({
  logisCenterProblemTypeList,
  INITINFO,
  checkPerm,
  loading: loading.effects['logisCenterProblemTypeList/fetch'],
}))
class TableList extends React.Component<TableListProps, TableListState> {
  columns: any = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '问题类型',
      dataIndex: 'name',
      width: 120,
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      width: 100,
      render: (text: number) => (text === 0 ? '已禁用' : '已启用'),
    },
    {
      title: '修改人',
      dataIndex: 'updateUser',
      width: 100,
    },
    {
      title: '签收状态',
      dataIndex: 'isPrint',
      width: 100,
      render: (text: number) => (text === 0 ? '不可签收' : '可签收'),
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      width: 180,
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 120,
      render: (id: any, record: any) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleOpenEditProblem(record)}
          >
            修改
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleCloseType(id, record.status === 0 ? 1 : 0)}
          >
            {record.status === 0 ? '启用' : '禁用'}
          </span>
        </>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 20,
    formValues: {},
    orderInfo: { status: '', isPrint: '' },
    problemDialog: false,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || 20,
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchTypeList();
    this.fetchProblemList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchProblemList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { formValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(formValues);
  }

  // 获取问题件类型
  fetchTypeList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'logisCenterProblemTypeList/typeList' });
  }

  // 获取问题件类型
  fetchProcessStatus = (problemType: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemTypeList/processStatus',
      payload: { problemType },
    });
  }

  // 获取数据
  fetchProblemList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemTypeList/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current: pageIndex, pageSize } = this.state;
    const params = { ...formValues, pageIndex, pageSize };

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '问题类型管理',
        url: `/logisCenter/problem/list/problemList?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '问题类型管理',
      url: '/logisCenter/problem/list/problemList',
      isTopMenu: true,
    });
  };

  /**
   * 确认投递
   */
  handleConfirmDelivery = (id: number, orderType: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemTypeList/confirm',
      payload: {
        query: this.getQueryParams(),
        params: { id, orderType },
      },
    });
  };

  /**
   * 取消投递
   */
  handleCancelDelivery = (id: number, orderType: number, openCell: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemTypeList/cancel',
      payload: {
        query: this.getQueryParams(),
        params: { id, orderType, openCell },
      },
    });
  };

  // 分页
  onSelectChange = (page: number, psize: number | undefined) => {
    const { formValues } = this.state;
    const query = { ...formValues, page, psize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '问题类型管理',
      url: `/logisCenter/problem/list/problemList?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  /**
   * 打开添加类型弹窗
   */
  handleOpenAddProblem = () => this.setState({ problemDialog: true });

  /**
   * 打开添加类型弹窗
   */
  handleOpenEditProblem = (orderInfo: any) => this.setState({ orderInfo, problemDialog: true });

  /**
   * 关闭添加类型弹窗
   */
  handleCloseProblem = () => {
    this.setState({
      problemDialog: false,
      orderInfo: { status: '', isPrint: '' },
    });
  }

  /**
   * 添加类型
   */
  handleAddProblem = () => {
    const { orderInfo } = this.state;

    if (!orderInfo.name) {
      message.error('名称不能为空！');
      return;
    }

    if (orderInfo.isPrint === '') {
      message.error('请选择是否可签收！');
      return;
    }

    if (orderInfo.status === '') {
      message.error('请选择状态！');
      return;
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemTypeList/addType',
      payload: {
        query: this.getQueryParams(),
        params: _.pick(orderInfo, ['id', 'name', 'isPrint', 'status']),
      },
    });

    this.handleCloseProblem();
  };

  /**
   * 禁用、启用类型
   */
  handleCloseType = (id: number, status: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemTypeList/closeType',
      payload: {
        query: this.getQueryParams(),
        params: { id, status },
      },
    });
  };

  /**
  * 输入运单号
  */
  handleChangeExpcode = (e: any) => this.changeOrderInfo('remark', e.target.value);

  /**
   * 输入问题件名称
   */
  handleChangeName = (e: any) => this.changeOrderInfo('name', e.target.value);

  /**
   * 选择问题件类型
   */
  handleChangeProblemType = (value: number) => this.changeOrderInfo('isPrint', value);

  /**
   * 选择处理状态
   */
  handleChangeStatus = (value: number) => this.changeOrderInfo('status', value);

  /**
  * 输入备注
  */
  handleChangeRemark = (e: any) => this.changeOrderInfo('remark', e.target.value);

  changeOrderInfo = (key:string, value:any) => {
    const { orderInfo } = this.state;
    orderInfo[key] = value;
    this.setState({ orderInfo });
  }


  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const { form: { getFieldDecorator } } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <FormItem label="问题类型" colon={false}>
              {getFieldDecorator('name')(
                <Input placeholder="请输入" />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="　　状态" colon={false}>
              {getFieldDecorator('status')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option value="1">已启用</Option>
                  <Option value="0">已禁用</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="签收状态" colon={false}>
              {getFieldDecorator('isPrint')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option value="1">可签收</Option>
                  <Option value="0">不可签收</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  // 渲染设置问题件
  renderProblemModalElem = () => {
    const { problemDialog, orderInfo } = this.state;
    const title = orderInfo.id ? '编辑问题件类型' : '添加问题件类型';

    return (
      <Modal
        title={title}
        visible={problemDialog}
        onOk={this.handleAddProblem}
        onCancel={this.handleCloseProblem}
      >
        <Form className="tableListForm">
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="问题件类型" colon={false}>
                <Input value={orderInfo.name} onChange={this.handleChangeName} />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="是否可签收" colon={false}>
                <Select
                  placeholder="请选择"
                  value={orderInfo.isPrint}
                  onChange={this.handleChangeProblemType}
                >
                  <Option value={1}>可签收</Option>
                  <Option value={0}>不可签收</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="问题件状态" colon={false}>
                <Select
                  placeholder="请选择"
                  value={orderInfo.status}
                  onChange={this.handleChangeStatus}
                >
                  <Option value={1}>已启用</Option>
                  <Option value={0}>已禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  }

  render() {
    const { current, pageSize } = this.state;
    const { logisCenterProblemTypeList: { data }, loading } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleOpenAddProblem}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={data.list || []}
            pagination={pagination}
            loading={loading}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        {this.renderProblemModalElem()}
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
